package com.gscitysfy.cus.drain.modules.pipe.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cloudfrmwk.data.mybatis.HerodotusIdentifierGenerator;
import com.gscitysfy.cus.drain.config.BusinessException;
import com.gscitysfy.cus.drain.constants.DistrictConverter;
import com.gscitysfy.cus.drain.modules.pipe.entity.DrainPipeHiddenDangerAnalyse;
import com.gscitysfy.cus.drain.modules.pipe.entity.DrainPipeHiddenDangerRequisition;
import com.gscitysfy.cus.drain.modules.pipe.mapper.DrainPipeHiddenDangerAnalyseMapper;
import com.gscitysfy.cus.drain.modules.pipe.service.IDrainPipeHiddenDangerAnalyseService;
import com.gscitysfy.cus.drain.modules.pipe.service.IDrainPipeHiddenDangerRequisitionService;
import com.gscitysfy.cus.drain.modules.pipe.vo.HiddenDangerAnalyseQueryVo;
import com.gscitysfy.cus.drain.modules.pipe.vo.HiddenDangerAnalyseVo;
import com.gscitysfy.cus.drain.utils.DateUtil;
import groovy.lang.Lazy;
import jodd.util.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.http.util.Asserts;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * <p>
 * 官网隐患分析 服务实现类
 * </p>
 *
 * @author Axi
 * @since 2022-11-16 12:06:33
 */
@Service
public class DrainPipeHiddenDangerAnalyseServiceImpl extends ServiceImpl<DrainPipeHiddenDangerAnalyseMapper, DrainPipeHiddenDangerAnalyse> implements IDrainPipeHiddenDangerAnalyseService {

    @Resource
    @Lazy
    IDrainPipeHiddenDangerRequisitionService requisitionService;

    /**
     * '管网隐患' 前缀
     */
    public static final String HIDDEN_DANGER_ANALYSE_PREFIX_WORD = "GWYH";

    /**
     * '隐患通知单' 前缀
     */
    public static final String HIDDEN_DANGER_REQUISITION_PREFIX_WORD = "YHTZD";

    /**
     * 未推送
     */
    public static final String HIDDEN_DANGER_REQUISITION_STATE_UNPUSH = "0";

    @Resource
    HerodotusIdentifierGenerator herodotusIdentifierGenerator;

    @Override
    public Boolean add(HiddenDangerAnalyseVo analyseVo) {
        DrainPipeHiddenDangerAnalyse analyse = new DrainPipeHiddenDangerAnalyse();
        BeanUtils.copyProperties(analyseVo, analyse);
        long id = herodotusIdentifierGenerator.nextId(analyse).longValue();
        analyse.setCmKid(id);
        //隐患的编号
        analyse.setHiddenDangerNo(generateHiddenDangerOrder());
        //通知单的编号
        DrainPipeHiddenDangerRequisition requisition = new DrainPipeHiddenDangerRequisition();
        long requisitionId = herodotusIdentifierGenerator.nextId(requisition).longValue();
        requisition.setCmKid(requisitionId);
        requisition.setHiddenDangerId(id);
        requisition.setRequisitionNo(generateRequisitionOrder());
        requisition.setRequisitionStatus(HIDDEN_DANGER_REQUISITION_STATE_UNPUSH);
        //新增隐患时同时生成通知单
        requisitionService.save(requisition);
        return this.save(analyse);
    }

    @Override
    public Boolean delete(String ids) {
        Asserts.notBlank(ids, "ids");
        List<Long> idList = Lists.newArrayList();
        Stream.of(ids.split(StrUtil.COMMA)).forEach(id -> {
            DrainPipeHiddenDangerAnalyse dangerAnalyse = this.getById(Long.parseLong(id));
            if (Objects.isNull(dangerAnalyse)) {
                throw new BusinessException("隐患数据不存在!");
            }
            idList.add(Long.parseLong(id));
        });
        return this.removeBatchByIds(idList);
    }

    @Override
    public Boolean update(HiddenDangerAnalyseVo analyseVo) {
        Asserts.notNull(analyseVo.getCmKid(), "cmkid");
        DrainPipeHiddenDangerAnalyse analyse = this.getById(analyseVo.getCmKid());
        if (Objects.isNull(analyse)) {
            throw new BusinessException("隐患数据不存在!");
        }
        DrainPipeHiddenDangerAnalyse updateVo = new HiddenDangerAnalyseVo();
        BeanUtils.copyProperties(analyseVo, updateVo);
        return this.updateById(updateVo);
    }

    @Override
    public IPage<DrainPipeHiddenDangerAnalyse> getPageList(HiddenDangerAnalyseQueryVo queryVo) {
        IPage<DrainPipeHiddenDangerAnalyse> page = new Page<>(queryVo.getCurrent(), queryVo.getSize());
        QueryWrapper<DrainPipeHiddenDangerAnalyse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(StringUtil.isNotBlank(queryVo.getHiddenDangerName()), DrainPipeHiddenDangerAnalyse::getHiddenDangerName, queryVo.getHiddenDangerName())
                .eq(StringUtil.isNotBlank(queryVo.getHiddenDangerSource()), DrainPipeHiddenDangerAnalyse::getHiddenDangerSource, queryVo.getHiddenDangerSource())
                .eq(StringUtil.isNotBlank(queryVo.getHiddenDangerCategory()), DrainPipeHiddenDangerAnalyse::getHiddenDangerCategory, queryVo.getHiddenDangerCategory())
                .eq(StringUtil.isNotBlank(queryVo.getHiddenDangerLevel()), DrainPipeHiddenDangerAnalyse::getHiddenDangerLevel, queryVo.getHiddenDangerLevel())
                .ge(StringUtil.isNotBlank(queryVo.getStart()), DrainPipeHiddenDangerAnalyse::getCmAddtime, queryVo.getStart())
                .le(StringUtil.isNotBlank(queryVo.getEnd()), DrainPipeHiddenDangerAnalyse::getCmAddtime, queryVo.getEnd());
        IPage<DrainPipeHiddenDangerAnalyse> analysePage = this.page(page, queryWrapper);
        if (CollectionUtils.isNotEmpty(analysePage.getRecords())) {
            analysePage.getRecords().forEach(item -> {
                if (!Objects.isNull(item.getCmRegflag())) {
                    item.setCmRegflagDesc(DistrictConverter.getDistrictName(String.valueOf(item.getCmRegflag())));
                }
            });
        }
        return analysePage;
    }

    /**
     * 隐患编号生成
     *
     * @return String 隐患编号
     */
    public String generateHiddenDangerOrder() {
        String code = HIDDEN_DANGER_ANALYSE_PREFIX_WORD + DateUtil.formatDate(new Date(), "yyyyMMdd");
        LambdaQueryWrapper<DrainPipeHiddenDangerAnalyse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(DrainPipeHiddenDangerAnalyse::getHiddenDangerNo, code).orderByDesc(DrainPipeHiddenDangerAnalyse::getCmAddtime).last("limit 1");
        DrainPipeHiddenDangerAnalyse analyse = this.getOne(queryWrapper);
        if (!Objects.isNull(analyse)) {
            String preNo = analyse.getHiddenDangerNo();
            String num = preNo.substring(preNo.length() - 4);
            String time = preNo.substring(0, preNo.length() - 4);
            DecimalFormat format = new DecimalFormat("0000");
            code = time + format.format(Integer.parseInt(num) + 1);
        } else {
            code = code + "0001";
        }
        return code;
    }

    /**
     * 生成通知单编号
     *
     * @return String 通知单编号
     */
    public String generateRequisitionOrder() {
        String code = HIDDEN_DANGER_REQUISITION_PREFIX_WORD + DateUtil.formatDate(new Date(), "yyyyMMdd");
        LambdaQueryWrapper<DrainPipeHiddenDangerRequisition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(DrainPipeHiddenDangerRequisition::getRequisitionNo, code).orderByDesc(DrainPipeHiddenDangerRequisition::getCmAddtime).last("limit 1");
        DrainPipeHiddenDangerRequisition analyse = requisitionService.getOne(queryWrapper);
        if (!Objects.isNull(analyse)) {
            String preNo = analyse.getRequisitionNo();
            String num = preNo.substring(preNo.length() - 4);
            String time = preNo.substring(0, preNo.length() - 4);
            DecimalFormat format = new DecimalFormat("0000");
            code = time + format.format(Integer.parseInt(num) + 1);
        } else {
            code = code + "0001";
        }
        return code;
    }
}
